package com.xyzwps.server.paimon.infra

import org.slf4j.LoggerFactory
import org.springframework.http.client.JdkClientHttpRequestFactory
import org.springframework.web.client.RestClient
import org.springframework.web.client.support.RestClientAdapter
import org.springframework.web.service.invoker.HttpServiceProxyFactory
import java.net.http.HttpClient
import java.time.Duration
import kotlin.reflect.KClass

object RestApisFactory {

    private val log = LoggerFactory.getLogger(RestApisFactory::class.java)

    fun <T : Any> create(c: KClass<T>): T {
        log.info("[RestApis] init {}", c.qualifiedName)

        val baseUrl = c.annotations
            .filter { it is RestApis }
            .map { it as RestApis }
            .firstOrNull()
            ?.baseUrl
            ?: throw IllegalArgumentException("[RestApis] ${c.qualifiedName} is not annotated with @RestApis")

        return httpServiceProxyFactory(baseUrl).createClient(c.java)
    }

    private fun restClient(baseUrl: String): RestClient {
        val connectTimeout = Duration.ofSeconds(5)
        val readTimeout = Duration.ofSeconds(5)
        val httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .connectTimeout(connectTimeout)
            .build()
        val httpRequestFactory = JdkClientHttpRequestFactory(httpClient)
        httpRequestFactory.setReadTimeout(readTimeout)
        return RestClient.builder()
            .requestFactory(httpRequestFactory)
            .baseUrl(baseUrl)
            .build()
    }

    private fun httpServiceProxyFactory(baseUrl: String): HttpServiceProxyFactory {
        val adapter = RestClientAdapter.create(restClient(baseUrl))
        return HttpServiceProxyFactory.builderFor(adapter).build()
    }
}